﻿using CMS.Dialogs.Notifications;
using System;
using System.Threading;
using System.Windows.Forms;

namespace CMS.Dialogs
{
    public partial class ProcessNotificationDialog : Form
    {
        private static INoticePublisher _Publisher;

        private static Thread _Thread;

        private static ProcessNotificationDialog _ProcessNotificationDialog;

        public string TaskName { get => TB_Title.Text; set => TB_Title.Text = value; }

        public static INoticePublisher Start(string title, INoticePublisher publisher = null)
        {
            _Publisher = publisher ?? new NoticePublisher();
            if (_Thread == null || !_Thread.IsAlive)
            {
                _Thread = new Thread(() =>
                {
                    _ProcessNotificationDialog = new ProcessNotificationDialog
                    {
                        TaskName = title
                    };
                    Application.Run(_ProcessNotificationDialog);
                    _ProcessNotificationDialog = null;
                    _Thread = null; ;
                });
                _Thread.Start();
            }
            else
            {
                _ProcessNotificationDialog.Invoke(new Action(() =>
                {
                    _ProcessNotificationDialog.TaskName = title;
                    if (_ProcessNotificationDialog.Visible)
                    {
                        _ProcessNotificationDialog.Focus();
                    }
                    else
                    {
                        _ProcessNotificationDialog.Show();
                    }
                }));
            }
            return _Publisher;
        }



        public ProcessNotificationDialog()
        {
            InitializeComponent();
        }


        private void T_Main_Tick(object sender, EventArgs e)
        {
            if (_Publisher != null)
            {
                while (_Publisher.Available())
                {
                    TB_Log.AppendText(_Publisher.ReadLine());
                }
            }
        }


        public void Stop()
        {
            _ProcessNotificationDialog?.Invoke(new Action(() =>
            {
                _ProcessNotificationDialog.Close();
            }));
        }

    }
}
